// pages/login/login.js
import { get } from '../../utils/request';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    errPaw: false,
    username: '',
    password: '',
    code: '',
    jssessionid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */

  getCode() {
    wx.request({
      url: `http://8.130.99.108:8090/api/getCaptchaCode`, //仅为示例，并非真实的接口地址
      responseType: 'arraybuffer',
      method: 'GET',
      success: (res) => {
        var cookies = res.header['Set-Cookie'];
        // 提取 jssessionid
        var jssessionid = cookies.match(/JSESSIONID=(\S*);/)[1];

        this.setData({
          jssessionid,
        });
        const base64 = wx.arrayBufferToBase64(res.data);
        this.setData({
          code: 'data:image/png;base64,' + base64,
        });
      },
      fail: (error) => {
        console.log(error);
      },
    });
  },

  onLoad(options) {
    this.getCode();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // const username = wx.getStorageSync('username')
    // const password = wx.getStorageSync('password')
    // if (username && password) {
    //   this.setData({
    //     username: username,
    //     password: password,
    //   })
    //   this.login()
    // }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideHomeButton();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  formSubmit(e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value);

    const { username, password, captchaCode } = e.detail.value;
    const { jssessionid } = this.data;
    console.log(e.detail.value);
    wx.request({
      url: `http://8.130.99.108:8090/api/login`, //仅为示例，并非真实的接口地址
      data: {
        username,
        password,
        captchaCode,
      },
      header: {
        'content-type': 'application/json', // 默认值
        cookie: 'JSESSIONID=' + jssessionid,
      },
      method: 'GET',
      success: (res) => {
        if (res.data.message == '服务运行成功') {
          const roleId = res.data.data.role;
          const personId = res.data.data.personId;
          try {
            wx.setStorageSync('userType', roleId);
            wx.setStorageSync('personId', personId);
          } catch (e) {
            console.log(e);
          }
          if (roleId == 0) {
            wx.switchTab({
              url: `/pages/goods/category/index`,
              success: (result) => {},
              fail: () => {},
              complete: () => {},
            });
          } else {
            wx.switchTab({
              url: `/pages/scanCode/scanCode`,
              success: (result) => {
                console.log(result);
              },
              fail: (e) => {
                console.log(e);
              },
              complete: (e) => {
                console.log(e);
              },
            });
          }
        } else if (res.data.message == '验证码错误') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '验证码错误,请刷新后重试',
          });
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '服务器错误,请稍微重试',
          });
        }
      },
      fail: (error) => {
        console.log(error);
      },
    });
  },

  toRegister() {
    wx.navigateTo({
      url: '/pages/register/register',
    });
  },
});
